package com.yiding.sys.common.auth;

import com.yiding.sys.common.enums.UserStatusEnum;
import com.yiding.sys.common.enums.ResultCodeEnum;
import com.yiding.sys.dao.SysUserMapper;
import com.yiding.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @author War horse imwarhorse@aliyun.com
 * Date: 2020/8/7
 * Description: [Shiro]自定义验证授权Realm
 */
public class AuthRealm extends AuthorizingRealm {

	@Resource
	private SysUserMapper sysUserMapper;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 授权
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		// 认证
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		String username = token.getUsername();

		// 根据用户名获取用户信息
		SysUser user = sysUserMapper.selectUserByUsername(username);
		if (user == null) {
			// 用户不存在
			throw new UnknownAccountException(ResultCodeEnum.CREDENTIALS_ILLEGAL.getName());
		}
		// 判断用户状态
		if (user.getStatus().equals(UserStatusEnum.INVALID.getStatus())) {
			// 如果用户为失效状态
			throw new LockedAccountException(ResultCodeEnum.LOCKED_ACCOUNT.getName());
		}

		Object principal = user;
		// 用户凭证，即密码。登录时用户输入的密码。
		Object hashedCredentials = user.getPassword();
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());

		// *** 注意看第一个参数principal，这个参数会在Shiro运行时流转到下流程序中（正经的下流），比如授权方法doGetAuthorizationInfo() ***
		AuthenticationInfo info = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, this.getName());
		return info;
	}
}
